<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>分类: 技术教程 | 小小程序员</title><meta name="author" content="十一星野"><meta name="copyright" content="十一星野"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Java 8 引入了全新的 Stream API，可以使用声明的方式来处理数据，极大地方便了集合操作，让我们可以使用更少的代码来实现更为复杂的逻辑，本文主要对一些常用的 Stream API 进行介绍。  #👍 相关视频教程Java 8 Stream API的使用open in new window #什么是Stream？Stream（流）是一个来自数据源的元素队列，它可以支持聚合操作。  数">
<meta property="og:type" content="article">
<meta property="og:title" content="Java 8都出那么久了，Stream API了解下？">
<meta property="og:url" content="https://ko25891wan.gitlab.io/2024/01/c8555c416d6c.html">
<meta property="og:site_name" content="小小程序员">
<meta property="og:description" content="Java 8 引入了全新的 Stream API，可以使用声明的方式来处理数据，极大地方便了集合操作，让我们可以使用更少的代码来实现更为复杂的逻辑，本文主要对一些常用的 Stream API 进行介绍。  #👍 相关视频教程Java 8 Stream API的使用open in new window #什么是Stream？Stream（流）是一个来自数据源的元素队列，它可以支持聚合操作。  数">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png">
<meta property="article:published_time" content="2024-01-21T09:27:59.000Z">
<meta property="article:modified_time" content="2024-01-21T09:27:59.554Z">
<meta property="article:author" content="十一星野">
<meta property="article:tag" content="宅男,热血">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://ko25891wan.gitlab.io/2024/01/c8555c416d6c.html"><link rel="preconnect" href="//fastly.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.5.1/css/all.min.css"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":1,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.staticfile.org/egjs-infinitegrid/4.11.0/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '分类: 技术教程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-01-21 17:27:59'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="小小程序员"><span class="site-name">小小程序员</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">Java 8都出那么久了，Stream API了解下？</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-01-21T09:27:59.000Z" title="发表于 2024-01-21 17:27:59">2024-01-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-01-21T09:27:59.554Z" title="更新于 2024-01-21 17:27:59">2024-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/">技术教程</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/">mall</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/%E6%8A%80%E6%9C%AF%E8%A6%81%E7%82%B9%E7%AF%87/">技术要点篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>5分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java 8都出那么久了，Stream API了解下？"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><blockquote>
<p>Java 8 引入了全新的 Stream API，可以使用声明的方式来处理数据，极大地方便了集合操作，让我们可以使用更少的代码来实现更为复杂的逻辑，本文主要对一些常用的 Stream API 进行介绍。</p>
</blockquote>
<h2 id="👍-相关视频教程"><a href="#👍-相关视频教程" class="headerlink" title="#👍 相关视频教程"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#%F0%9F%91%8D-%E7%9B%B8%E5%85%B3%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B">#</a>👍 相关视频教程</h2><p><a target="_blank" rel="noopener" href="https://t.zsxq.com/0ehzsNr7R">Java 8 Stream API的使用open in new window</a></p>
<h2 id="什么是Stream？"><a href="#什么是Stream？" class="headerlink" title="#什么是Stream？"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#%E4%BB%80%E4%B9%88%E6%98%AFstream">#</a>什么是Stream？</h2><p>Stream（流）是一个来自数据源的元素队列，它可以支持聚合操作。</p>
<ul>
<li>数据源：流的数据来源，构造Stream对象的数据源，比如通过一个List来构造Stream对象，这个List就是数据源；</li>
<li>聚合操作：对Stream对象进行处理后使得Stream对象返回指定规则数据的操作称之为聚合操作，比如filter、map、limit、sorted等都是聚合操作。</li>
</ul>
<h2 id="Stream-聚合操作"><a href="#Stream-聚合操作" class="headerlink" title="#Stream 聚合操作"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#stream-%E8%81%9A%E5%90%88%E6%93%8D%E4%BD%9C">#</a>Stream 聚合操作</h2><h3 id="背景介绍"><a href="#背景介绍" class="headerlink" title="#背景介绍"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#%E8%83%8C%E6%99%AF%E4%BB%8B%E7%BB%8D">#</a>背景介绍</h3><p>本文将以mall中的UmsPermission对象为例来介绍Stream API的常用操作。UmsPermission是一个权限对象，主要分为三种权限，目录、菜单以及按钮，对象定义如下。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">public class UmsPermission implements Serializable &#123;</span><br><span class="line">    private Long id;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;父级权限id&quot;)</span><br><span class="line">    private Long pid;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;名称&quot;)</span><br><span class="line">    private String name;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;权限值&quot;)</span><br><span class="line">    private String value;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;图标&quot;)</span><br><span class="line">    private String icon;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;权限类型：0-&gt;目录；1-&gt;菜单；2-&gt;按钮（接口绑定权限）&quot;)</span><br><span class="line">    private Integer type;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;前端资源路径&quot;)</span><br><span class="line">    private String uri;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;启用状态；0-&gt;禁用；1-&gt;启用&quot;)</span><br><span class="line">    private Integer status;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;创建时间&quot;)</span><br><span class="line">    private Date createTime;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;排序&quot;)</span><br><span class="line">    private Integer sort;</span><br><span class="line"></span><br><span class="line">    private static final long serialVersionUID = 1L;</span><br><span class="line">    </span><br><span class="line">    //省略所有getter及setter方法</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Stream对象的创建"><a href="#Stream对象的创建" class="headerlink" title="#Stream对象的创建"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#stream%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%88%9B%E5%BB%BA">#</a>Stream对象的创建</h3><p>Stream对象分为两种，一种串行的流对象，一种并行的流对象。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">// permissionList指所有权限列表</span><br><span class="line">// 为集合创建串行流对象</span><br><span class="line">Stream&lt;UmsPermission&gt; stream = permissionList.stream();</span><br><span class="line">// 为集合创建并行流对象</span><br><span class="line">Stream&lt;UmsPermission&gt; parallelStream = permissionList.parallelStream();</span><br></pre></td></tr></table></figure>

<h3 id="filter"><a href="#filter" class="headerlink" title="#filter"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#filter">#</a>filter</h3><p>对Stream中的元素进行过滤操作，当设置条件返回true时返回相应元素。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// 获取权限类型为目录的权限</span><br><span class="line">List&lt;UmsPermission&gt; dirList = permissionList.stream()</span><br><span class="line">    .filter(permission -&gt; permission.getType() == 0)</span><br><span class="line">    .collect(Collectors.toList());</span><br></pre></td></tr></table></figure>

<h3 id="map"><a href="#map" class="headerlink" title="#map"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#map">#</a>map</h3><p>对Stream中的元素进行转换处理后获取。比如可以将UmsPermission对象转换成Long对象。 我们经常会有这样的需求：需要把某些对象的id提取出来，然后根据这些id去查询其他对象，这时可以使用此方法。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// 获取所有权限的id组成的集合</span><br><span class="line">List&lt;Long&gt; idList = permissionList.stream()</span><br><span class="line">    .map(permission -&gt; permission.getId())</span><br><span class="line">    .collect(Collectors.toList());</span><br></pre></td></tr></table></figure>

<h3 id="limit"><a href="#limit" class="headerlink" title="#limit"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#limit">#</a>limit</h3><p>从Stream中获取指定数量的元素。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// 获取前5个权限对象组成的集合</span><br><span class="line">List&lt;UmsPermission&gt; firstFiveList = permissionList.stream()</span><br><span class="line">    .limit(5)</span><br><span class="line">    .collect(Collectors.toList());</span><br></pre></td></tr></table></figure>

<h3 id="count"><a href="#count" class="headerlink" title="#count"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#count">#</a>count</h3><p>仅获取Stream中元素的个数。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// count操作：获取所有目录权限的个数</span><br><span class="line">long dirPermissionCount = permissionList.stream()</span><br><span class="line">    .filter(permission -&gt; permission.getType() == 0)</span><br><span class="line">    .count();</span><br></pre></td></tr></table></figure>

<h3 id="sorted"><a href="#sorted" class="headerlink" title="#sorted"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#sorted">#</a>sorted</h3><p>对Stream中元素按指定规则进行排序。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// 将所有权限按先目录后菜单再按钮的顺序排序</span><br><span class="line">List&lt;UmsPermission&gt; sortedList = permissionList.stream()</span><br><span class="line">    .sorted((permission1,permission2)-&gt;&#123;return permission1.getType().compareTo(permission2.getType());&#125;)</span><br><span class="line">    .collect(Collectors.toList());</span><br></pre></td></tr></table></figure>

<h3 id="skip"><a href="#skip" class="headerlink" title="#skip"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#skip">#</a>skip</h3><p>跳过指定个数的Stream中元素，获取后面的元素。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// 跳过前5个元素，返回后面的</span><br><span class="line">List&lt;UmsPermission&gt; skipList = permissionList.stream()</span><br><span class="line">    .skip(5)</span><br><span class="line">    .collect(Collectors.toList());</span><br></pre></td></tr></table></figure>

<h3 id="用collect方法将List转成map"><a href="#用collect方法将List转成map" class="headerlink" title="#用collect方法将List转成map"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#%E7%94%A8collect%E6%96%B9%E6%B3%95%E5%B0%86list%E8%BD%AC%E6%88%90map">#</a>用collect方法将List转成map</h3><p>有时候我们需要反复对List中的对象根据id进行查询，我们可以先把该List转换为以id为key的map结构，然后再通过map.get(id)来获取对象，这样比较方便。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">// 将权限列表以id为key，以权限对象为值转换成map</span><br><span class="line">Map&lt;Long, UmsPermission&gt; permissionMap = permissionList.stream()</span><br><span class="line">    .collect(Collectors.toMap(permission -&gt; permission.getId(), permission -&gt; permission));</span><br></pre></td></tr></table></figure>

<h2 id="应用"><a href="#应用" class="headerlink" title="#应用"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#%E5%BA%94%E7%94%A8">#</a>应用</h2><blockquote>
<p>我们经常会有返回树形结构数据的需求。比如这里的权限，第一层是目录权限，目录权限之下有菜单权限，菜单权限之下有按钮权限。如果我们要返回一个集合，包含目录权限，目录权限下面嵌套菜单权限，菜单权限下嵌套按钮权限。使用Stream API可以很方便的解决这个问题。</p>
</blockquote>
<p><strong>注意：这里我们的权限上下级之间以pid来关联，pid是指上一级权限的id，顶级权限的id为0。</strong></p>
<h3 id="定义包含下级权限的对象"><a href="#定义包含下级权限的对象" class="headerlink" title="#定义包含下级权限的对象"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#%E5%AE%9A%E4%B9%89%E5%8C%85%E5%90%AB%E4%B8%8B%E7%BA%A7%E6%9D%83%E9%99%90%E7%9A%84%E5%AF%B9%E8%B1%A1">#</a>定义包含下级权限的对象</h3><p>继承自UmsPermission对象，之增加了一个children属性，用于存储下级权限。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Created by macro on 2018/9/30.</span><br><span class="line"> */</span><br><span class="line">public class UmsPermissionNode extends UmsPermission &#123;</span><br><span class="line">    private List&lt;UmsPermissionNode&gt; children;</span><br><span class="line"></span><br><span class="line">    public List&lt;UmsPermissionNode&gt; getChildren() &#123;</span><br><span class="line">        return children;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setChildren(List&lt;UmsPermissionNode&gt; children) &#123;</span><br><span class="line">        this.children = children;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="定义获取树形结构的方法"><a href="#定义获取树形结构的方法" class="headerlink" title="#定义获取树形结构的方法"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#%E5%AE%9A%E4%B9%89%E8%8E%B7%E5%8F%96%E6%A0%91%E5%BD%A2%E7%BB%93%E6%9E%84%E7%9A%84%E6%96%B9%E6%B3%95">#</a>定义获取树形结构的方法</h3><p>我们先过滤出pid为0的顶级权限，然后给每个顶级权限设置其子级权限，covert方法的主要用途就是从所有权限中找出相应权限的子级权限。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public List&lt;UmsPermissionNode&gt; treeList() &#123;</span><br><span class="line">    List&lt;UmsPermission&gt; permissionList = permissionMapper.selectByExample(new UmsPermissionExample());</span><br><span class="line">    List&lt;UmsPermissionNode&gt; result = permissionList.stream()</span><br><span class="line">            .filter(permission -&gt; permission.getPid().equals(0L))</span><br><span class="line">            .map(permission -&gt; covert(permission, permissionList)).collect(Collectors.toList());</span><br><span class="line">    return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="为每个权限设置子级权限"><a href="#为每个权限设置子级权限" class="headerlink" title="#为每个权限设置子级权限"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#%E4%B8%BA%E6%AF%8F%E4%B8%AA%E6%9D%83%E9%99%90%E8%AE%BE%E7%BD%AE%E5%AD%90%E7%BA%A7%E6%9D%83%E9%99%90">#</a>为每个权限设置子级权限</h3><p>这里我们使用filter操作来过滤出每个权限的子级权限，由于子级权限下面可能还会有子级权限，这里我们使用递归来解决。但是递归操作什么时候停止，这里把递归调用方法放到了map操作中去，当没有子级权限时filter下的map操作便不会再执行，从而停止递归。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">* 将权限转换为带有子级的权限对象</span><br><span class="line">* 当找不到子级权限的时候map操作不会再递归调用covert</span><br><span class="line">*/</span><br><span class="line">private UmsPermissionNode covert(UmsPermission permission, List&lt;UmsPermission&gt; permissionList) &#123;</span><br><span class="line">    UmsPermissionNode node = new UmsPermissionNode();</span><br><span class="line">    BeanUtils.copyProperties(permission, node);</span><br><span class="line">    List&lt;UmsPermissionNode&gt; children = permissionList.stream()</span><br><span class="line">           .filter(subPermission -&gt; subPermission.getPid().equals(permission.getId()))</span><br><span class="line">           .map(subPermission -&gt; covert(subPermission, permissionList)).collect(Collectors.toList());</span><br><span class="line">    node.setChildren(children);</span><br><span class="line">    return node;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="项目源码地址"><a href="#项目源码地址" class="headerlink" title="#项目源码地址"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/java_stream.html#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80">#</a>项目源码地址</h2><p><a target="_blank" rel="noopener" href="https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-stream">https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-stream</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io">十一星野</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io/2024/01/c8555c416d6c.html">https://ko25891wan.gitlab.io/2024/01/c8555c416d6c.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://ko25891wan.gitlab.io" target="_blank">小小程序员</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2024/01/058980b58e97.html" title="MyBatis Generator使用过程中踩过的一个坑"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">MyBatis Generator使用过程中踩过的一个坑</div></div></a></div><div class="next-post pull-right"><a href="/2024/01/d8d5c5f413d7.html" title="Elasticsearch项目实战，商品搜索功能设计与实现！"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Elasticsearch项目实战，商品搜索功能设计与实现！</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">十一星野</div><div class="author-info__description">归途也还可爱</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Gitlab"><i class="fab fa-gitlab" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:ko25891wan@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%F0%9F%91%8D-%E7%9B%B8%E5%85%B3%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">👍 相关视频教程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFStream%EF%BC%9F"><span class="toc-number">2.</span> <span class="toc-text">什么是Stream？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Stream-%E8%81%9A%E5%90%88%E6%93%8D%E4%BD%9C"><span class="toc-number">3.</span> <span class="toc-text">Stream 聚合操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%83%8C%E6%99%AF%E4%BB%8B%E7%BB%8D"><span class="toc-number">3.1.</span> <span class="toc-text">背景介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Stream%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="toc-number">3.2.</span> <span class="toc-text">Stream对象的创建</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#filter"><span class="toc-number">3.3.</span> <span class="toc-text">filter</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#map"><span class="toc-number">3.4.</span> <span class="toc-text">map</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#limit"><span class="toc-number">3.5.</span> <span class="toc-text">limit</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#count"><span class="toc-number">3.6.</span> <span class="toc-text">count</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#sorted"><span class="toc-number">3.7.</span> <span class="toc-text">sorted</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#skip"><span class="toc-number">3.8.</span> <span class="toc-text">skip</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8collect%E6%96%B9%E6%B3%95%E5%B0%86List%E8%BD%AC%E6%88%90map"><span class="toc-number">3.9.</span> <span class="toc-text">用collect方法将List转成map</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BA%94%E7%94%A8"><span class="toc-number">4.</span> <span class="toc-text">应用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E5%8C%85%E5%90%AB%E4%B8%8B%E7%BA%A7%E6%9D%83%E9%99%90%E7%9A%84%E5%AF%B9%E8%B1%A1"><span class="toc-number">4.1.</span> <span class="toc-text">定义包含下级权限的对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E8%8E%B7%E5%8F%96%E6%A0%91%E5%BD%A2%E7%BB%93%E6%9E%84%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-number">4.2.</span> <span class="toc-text">定义获取树形结构的方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BA%E6%AF%8F%E4%B8%AA%E6%9D%83%E9%99%90%E8%AE%BE%E7%BD%AE%E5%AD%90%E7%BA%A7%E6%9D%83%E9%99%90"><span class="toc-number">4.3.</span> <span class="toc-text">为每个权限设置子级权限</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80"><span class="toc-number">5.</span> <span class="toc-text">项目源码地址</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/c60470b9a892.html" title="Java集合使用注意事项总结">Java集合使用注意事项总结</a><time datetime="2024-02-03T04:58:22.000Z" title="发表于 2024-02-03 12:58:22">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/81fb7a201f29.html" title="无题">无题</a><time datetime="2024-02-03T03:15:31.812Z" title="发表于 2024-02-03 11:15:31">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/5737c1ec69a9.html" title="Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)">Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)</a><time datetime="2024-01-31T06:56:16.000Z" title="发表于 2024-01-31 14:56:16">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/f510db7d2f19.html" title="Spring常见面试题总结">Spring常见面试题总结</a><time datetime="2024-01-31T06:55:58.000Z" title="发表于 2024-01-31 14:55:58">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/9be065e9f288.html" title="redis 面试">redis 面试</a><time datetime="2024-01-31T06:55:55.000Z" title="发表于 2024-01-31 14:55:55">2024-01-31</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By 十一星野</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.staticfile.org/instant.page/5.2.0/instantpage.min.js" type="module"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>